package com.sfac.listener;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import javax.servlet.annotation.WebListener;
import java.io.File;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

/**
 * @Author:唐琳的爹
 * @BelongsProject:hqyj_springboot
 * @BelongsPackage:com.sfac.listener
 * @CreateTime:2022/8/22 09:51:59
 * @ClassName:LogListener
 */
// 监听器分为session监听器，上下文监听器，request请求监听器等
@WebListener
public class LogListener implements ServletContextListener {

    private final static Logger LOGGER = LoggerFactory.getLogger(LogListener.class);

    @Override
    public void contextInitialized(ServletContextEvent sce) {
        LOGGER.info("初始化方法");
        // 1.获取/var/log中的日志文件夹,判断是否存在,如果不存在则直接返回
        File file = new File("/var/log");
        if (file == null)return;
        // 获取当前日期字符串
        DateTimeFormatter dtf =DateTimeFormatter.ofPattern("yyyy-MM-dd");
        String currentDateString = dtf.format(LocalDateTime.now());
        // /var/log下日志文件列表，循环判断文件是否包含日期字符串,不包含则删除
        File[] files = file.listFiles();
        for (File f : files){
            String name = f.getName();
            if (!name.contains(currentDateString))f.delete();
        }
    }

    @Override
    public void contextDestroyed(ServletContextEvent sce) {
        LOGGER.info("销毁方法");
    }
}
